package com.example.ibsp_demo.controller.homePagePush.location;


import com.example.ibsp_demo.service.location.LocationServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/location")
public class LocationController {

    @Autowired
    private LocationServiceImpl locationService;

    // 获取当前用户所在城市
    @GetMapping("/current-city")
    public Map<String, Object> getCurrentCity(HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();

        // 1. 优先尝试从请求头获取用户IP
        String clientIp = getClientIp(request);

        // 2. 调用服务获取城市信息
        String city = locationService.getCityByIp(clientIp);

        // 3. 返回结果
        result.put("success", city != null);
        result.put("city", city);
        return result;
    }

    // 根据经纬度获取城市信息
    @PostMapping("/city")
    public Map<String, Object> getCityByCoordinates(
            @RequestParam double longitude,
            @RequestParam double latitude) {
        Map<String, Object> result = new HashMap<>();
        String city = locationService.getCityByCoordinates(longitude, latitude);
        result.put("success", city != null);
        result.put("city", city);
        return result;
    }

    // 获取客户端IP地址
    private String getClientIp(HttpServletRequest request) {
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader == null) {
            return request.getRemoteAddr();
        }
        return xffHeader.split(",")[0];
    }
}